<template>
  <el-upload
  class="upload-demo"
  :action="httpAddress"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :on-error="handleErrer"
  :before-upload="handleBefore"
  :on-success="handleSuccess"
  :file-list="fileList"
  :data="importObj"
  :headers="headersObj">
  <el-button type="primary">点击上传</el-button>
  <!-- <div slot="tip" class="el-upload__tip" v-if="type">{{message[type - 1]}}</div> -->
  </el-upload>
</template>
<script>
  export default {
    data () {
      return {
        fileList: [],
        message: ['只能上传以jpeg/jpg/png/gif结尾的文件', '只能上传以xls/xlsx结尾的文件'],
        headersObj: {
          'login-key': window.localStorage.loginKey
        }
      }
    },
    props: {
      type: {
        type: Number // type 1: 上传图片 2: 上传excel等文件 什么不传 则为不做判断
      },
      successCallback: {
        type: Function, // 上传成功的回调
        required: true
      },
      removeCallback: {
        type: Function, // 移除表格的回调
        required: true
      },
      importObj: {
        type: Object // 上传的额外参数
      },
      httpAddress: {
        type: String // 上传的地址
      }
    },
    methods: {
      handleRemove (file, fileList) {
        this.removeCallback(file, fileList)
      },
      handlePreview (file) {
        console.log(file)
      },
      handleErrer (file, file2) {
        console.log(file, file2)
        this.$message.error('上传失败,请从新上传')
      },
      handleBefore (file) {
        let type = ''
        if (this.type === 1) { // 判断上传文件条件 type 1 上传图片 2 上传excel等文件 什么不传 则为不做判断
          type = ['jpeg', 'jpg', 'png', 'gif']
        } else if (this.type === 2) {
          type = ['xls', 'xlsx']
        }
        let flag = type.some(val => {
          return file.name.endsWith(`.${val}`)
        })
        if (!flag) {
          if (type) {
            this.$alert(`请上传以.${type.join(',或.')}结尾的文件`, '上传失败', {
              confirmButtonText: '确定'
            })
          }
          return flag
        }
      },
      handleSuccess (response, file, fileList) {
        this.fileList = []
        if (Number(response.errcode)) {
          this.$alert(response.errmsg, '上传失败', {
            confirmButtonText: '确定'
          })
        } else {
          this.successCallback(response, file, fileList)
        }
      }
    }
  }
</script>